<template>
  <div class="monitor-page">
    <!-- 页面结构不变 -->
    <div class="patrol-grid">
      <div v-if="paginatedList.length === 0" class="empty-data-card">根据当前筛选条件，暂无巡逻记录</div>
      <div v-for="patrol in paginatedList" :key="patrol.shiftId" class="patrol-card">
        <div class="card-header">
          <h4 class="title">{{ getOfficerNames(patrol) }} - {{ patrol.location }}</h4>
        </div>
        <div class="card-body">
          <div class="info-row">
            <span class="label">状态:</span>
            <span :class="['status-badge', `status-${patrol.status}`]">{{ patrol.status }}</span>
          </div>
          <div class="info-row"><span class="label">开始时间:</span> <span class="value">{{ `${patrol.date} ${patrol.startTime}` }}</span></div>
          <div class="info-row"><span class="label">结束时间:</span> <span class="value">{{ `${patrol.date} ${patrol.endTime}` }}</span></div>
          <div class="info-row"><span class="label">巡逻路线:</span> <span class="value">{{ patrol.route }}</span></div>
        </div>
        <div class="card-footer">
          <button class="btn-detail" @click="openDetailModal(patrol)">查看详情</button>
        </div>
      </div>
    </div>

    <!-- 分页控件 -->
    <div class="pagination-controls">
      <button @click="handlePageChange(currentPage - 1)" :disabled="currentPage <= 1">上一页</button>
      <span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
      <button @click="handlePageChange(currentPage + 1)" :disabled="currentPage >= totalPages">下一页</button>
    </div>

    <!-- 添加模态框组件 -->
    <PatrolDetailModal
      v-if="isModalOpen"
      :patrol="selectedPatrol"
      @close="closeModal"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue';
import PatrolDetailModal from './PatrolDetailModal.vue';
import * as XLSX from 'xlsx';
import api from '@/utils/axios'

const API_BASE = 'http://localhost:8080/api/auth/shifts';


// 计算巡逻任务状态的函数
const calculatePatrolStatus = (patrolPoints: any[]) => {

  if (!patrolPoints || patrolPoints.length === 0) {
    return '未知';
  }

  const totalPoints = patrolPoints.length;
  const signedPoints = patrolPoints.filter(point => point.status === 1).length;

  if (signedPoints === totalPoints) {
    return '已完成';
  } else if (signedPoints > 0) {
    return '进行中';
  } else {
    return '未开始';
  }
};

// 从后端获取巡逻记录
const fetchPatrolList = async () => {
  try {
    const response = await api.get(`${API_BASE}/all/with-collections`, {
      params: { keyword: '' }
    });
    patrolList.value = response.data.data.map(shift => {
      // 提取所有巡逻点
      const patrolPoints = shift.patrolPointCollections.flatMap(collection =>
        collection.patrolPoints
      );

      // 计算巡逻状态
      const status = calculatePatrolStatus(patrolPoints);

      return {
        shiftId: shift.shiftId,
        officerNames: shift.officers.map(officer => officer.name),
        location: shift.patrolPointCollections.map(item => item.patrolName).join(","),
        status,
        date: shift.date,
        startTime: shift.startTime,
        endTime:shift.endTime,
        // 从 patrolPoints 中提取巡逻点名称并拼接
        route: shift.patrolPointCollections
          .flatMap(collection => collection.patrolPoints)
          .map(point => point.pointName)
          .join(" → ")
      };
    });
  } catch (error) {
    console.error('获取巡逻记录失败:', error);
  }
};

// 初始化巡逻记录
const patrolList = ref([]);
fetchPatrolList();

// 筛选与分页逻辑不变
const filters = reactive({ keyword: '', status: '全部' });
const activeFilters = reactive({ keyword: '', status: '全部' });
const applyFilters = () => { Object.assign(activeFilters, filters); };
const resetFilters = () => { Object.assign(filters, { keyword: '', status: '全部' }); applyFilters(); };

const filteredList = computed(() => {
  return patrolList.value.filter(p => {
    const statusMatch = activeFilters.status === '全部' || p.status === activeFilters.status;
    const keyword = activeFilters.keyword.trim().toLowerCase();
    const keywordMatch = !keyword ||
      (p.officerNames && p.officerNames.some(name => name.toLowerCase().includes(keyword))) ||
      (p.location && p.location.toLowerCase().includes(keyword)) ||
      (p.route && p.route.toLowerCase().includes(keyword)) ||
      (p.status && p.status.toLowerCase().includes(keyword));
    return statusMatch && keywordMatch;
  });
});

const currentPage = ref(1);
const itemsPerPage = ref(6);
const totalPages = computed(() => Math.ceil(filteredList.value.length / itemsPerPage.value));
const paginatedList = computed(() => {
  const start = (currentPage.value - 1) * itemsPerPage.value;
  return filteredList.value.slice(start, start + itemsPerPage.value);
});
const handlePageChange = (page: number) => { currentPage.value = page; };
watch(activeFilters, () => { currentPage.value = 1; });

// 弹窗逻辑不变
const isModalOpen = ref(false);
const selectedPatrol = ref<any>(null);
const openDetailModal = (patrol: any) => { selectedPatrol.value = patrol; isModalOpen.value = true; };
const closeModal = () => { isModalOpen.value = false; };

// 辅助函数不变
const getOfficerNames = (patrol: any) => {
  return patrol.officerNames.join(', ');
};

// 导出数据到 Excel
const exportToExcel = () => {
  if (filteredList.value.length === 0) {
    alert('没有可导出的数据！');
    return;
  }

  const dataToExport = filteredList.value.map(p => ({
    '警员': p.officerNames.join(', '),
    '区域': p.location,
    '状态': p.status,
    '开始时间': `${p.date} ${p.time}`,
    '结束时间': '暂无信息',
    '巡逻路线': p.route
  }));

  const worksheet = XLSX.utils.json_to_sheet(dataToExport);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, '巡逻记录');
  XLSX.writeFile(workbook, `巡逻记录_${new Date().toLocaleDateString().replace(/\//g, '-')}.xlsx`);
};
</script>

<style scoped>
@import "@/assets/styles/views/dashboard/Monitor.css";

.pagination-controls {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.pagination-controls button {
  padding: 5px 15px;
  margin: 0 10px;
  cursor: pointer;
}

.pagination-controls button:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.pagination-controls span {
  align-self: center;
}
/* 新增的状态样式 */
.status-badge {
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  display: inline-block;
}

.status-未开始 {
  background-color: #f0ad4e;
  color: #fff;
}

.status-进行中 {
  background-color: #5bc0de;
  color: #fff;
}

.status-已完成 {
  background-color: #5cb85c;
  color: #fff;
}

.status-未知 {
  background-color: #777;
  color: #fff;
}
</style>

